package org.ribizli.games.amoeba;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Application;
import android.preference.PreferenceManager;

public class ApplicationEx extends Application {
  private final static String TAG = "ApplicationEx";
  private HttpClient mHTTPClient;
  private BackgroudService mBGService;

  @Override
  public void onCreate() {
    super.onCreate();
    mHTTPClient = createHttpClient();
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    shutdownHttpClient();
  }

  @Override
  public void onTerminate() {
    super.onTerminate();
    shutdownHttpClient();
  }
  
  private HttpClient createHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(params, getResources().getString(R.string.userAgent));
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUseExpectContinue(params, true);
    
    int timeout = Integer.parseInt(getResources().getString(R.string.connection_timeout)) * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    
    SchemeRegistry reg = new SchemeRegistry();
    reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    reg.register(new Scheme("https", org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager cmgr = new ThreadSafeClientConnManager(params, reg);
    
    return new DefaultHttpClient(cmgr, params);
  }
  
  private void shutdownHttpClient() {
    if (mHTTPClient != null && mHTTPClient.getConnectionManager() != null) {
      mHTTPClient.getConnectionManager().shutdown();
    }
  }
  
  public HttpClient getHttpClient() {
    return mHTTPClient;
  }
  
  public BackgroudService getBackgroudService() {
    if (mBGService == null) {
      mBGService = new BackgroudService(this);
    }
    return mBGService;
  }

}
